package com.nmu.app.Shrimp.veiw.javagame.render;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;

import com.nmu.app.Shrimp.veiw.javagame.Base2DGameStruct;
import com.nmu.app.Shrimp.veiw.javagame.IVisableObject;
import com.nmu.app.Shrimp.veiw.javagame.util.KeyboardInput;
import com.nmu.app.Shrimp.veiw.javagame.util.MouseInput;

/**2d游戏基础框架
 * 
 * @author hackM
 *
 */
public class Base2DGameEngine extends JFrame implements Runnable,Base2DGameStruct{
	protected volatile boolean running;
	protected Thread gameThread;
	protected BufferStrategy bufferStrategy;
	protected KeyboardInput keyboard;  
	protected MouseInput mouseInput;
	protected List<IVisableObject> visableObjects=new ArrayList<IVisableObject>();
	protected Canvas canvas=new Canvas();

	
	
	
	private void sleep(long sleep){
		try{
			Thread.sleep(sleep);
		}catch(InterruptedException e){}
	}	
	protected void onWindowClosing(){
		try{
			running=false;
			gameThread.join();
		}catch( InterruptedException e){
			e.printStackTrace();
		}
		System.exit(0);
	}	
	
	
	
	@Override
	public void run() {
		running=true;
		while(running){
			gameLoop();
		}
	}


	@Override
	public void createAndShowGUI() {
		canvas.setSize(640, 480);
		canvas.setBackground(Color.WHITE);
		canvas.setIgnoreRepaint(true);
		getContentPane().add(canvas);
		//
		pack();
		keyboard=new KeyboardInput();
		canvas.addKeyListener(keyboard);
		mouseInput=new MouseInput();
		canvas.addMouseListener(mouseInput);
		canvas.addMouseMotionListener(mouseInput);
		canvas.addMouseWheelListener(mouseInput);
		setVisible(true);
		//
		canvas.createBufferStrategy(2);
		bufferStrategy=canvas.getBufferStrategy();
		canvas.requestFocus();
	}


	@Override
	public void gameLoop() {
		processInput();
		updateObject();
		renderFrame();
		sleep(15);
	}


	@Override
	public void updateObject() {
		for(IVisableObject obj:visableObjects){
			obj.update(new Point(0,0));
		}
		
	}


	@Override
	public void renderFrame() {
		do{
			do{
				Graphics g=null;
				try{
					g=bufferStrategy.getDrawGraphics();
					//清除
					g.clearRect(0, 0, getWidth(), getHeight());
					//重绘
					for(IVisableObject iVisableObject:visableObjects){
						iVisableObject.render(g);
					}
				}finally{
					if(null!=g)g.dispose();
				}
			}while(bufferStrategy.contentsRestored());
			bufferStrategy.show();
		}while(bufferStrategy.contentsLost());		
	}


	@Override
	public void processInput() {
		mouseInput.poll();
		keyboard.poll();
		for(IVisableObject obj:visableObjects){
			obj.mouseProcess(mouseInput);
			obj.inputProcess(keyboard);
		}		
	}
	
	

}
